package task.presentation
{
    import flash.display.DisplayObject;

    import org.flexthinker.binding.form.FormModel;
    import org.flexthinker.binding.ui.form.binding.BindableUIForm;
    import org.flexthinker.binding.ui.form.binding.Binder;
    import org.flexthinker.binding.ui.form.binding.flex.TextBinder;
    import org.flexthinker.binding.ui.form.binding.support.FormBinding;

    import spark.components.Label;
    import spark.components.RichText;
    import spark.components.supportClasses.SkinnableComponent;

    import task.domain.converters.CategoryToStringConverter;

    /**
     * View displaying a <code>Task</code> in read-only mode.
     */
    public class TaskView extends SkinnableComponent implements BindableUIForm
    {
        [SkinPart]
        public var category:Label;
        [SkinPart]
        public var title:RichText;
        [SkinPart]
        public var description:RichText;
        [SkinPart]
        public var priority:Label;
        [SkinPart]
        public var isPublic:Label;

        private var _formModel:FormModel;

        private var formBinding:FormBinding;

        public function TaskView()
        {
            super();
        }

        public function set formModel( formModel:FormModel ):void
        {
            _formModel = formModel;
            bind();
        }


        public function getBindableElements():Vector.<DisplayObject>
        {
            return new <DisplayObject>[title,  description, priority, isPublic];
        }

        public function updateBindingState(pause:Boolean):void
        {
            if ( pause )
            {
                formBinding.unbind();
            }
            else if ( !formBinding.isBound )
            {
                formBinding.bind();
            }
        }

        // --------------------
        //   internal methods
        // --------------------

        private function bind():void
        {
            if ( formBinding )
            {
                formBinding.unbind();
            }
            formBinding = new FormBinding(this,_formModel);

            // category needs a special Converter, to be able to convert the object into a string format
            var categoryBinder:Binder = new TextBinder(category, "category");
            categoryBinder.getBinding(_formModel).setConverter( new CategoryToStringConverter() );
            formBinding.addFieldBinder(categoryBinder);

            // mark to auto bind ui fields; field name must match model property name
            formBinding.autoBind();
            //start binding
            formBinding.bind();
        }

    }
}
